package com.le.ssm.controller;

import com.le.ssm.core.constants.CommonConstants;
import com.le.ssm.core.entity.AjaxResult;
import com.le.ssm.core.exception.LoginException;
import com.le.ssm.model.Address;
import com.le.ssm.service.AddressService;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/user")
@AllArgsConstructor
@Log4j
public class UserController {
    private AddressService addressService;
    //    @Override
//    protected ModelAndView handleRequestInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
//        return new ModelAndView("user/list");
//    }
    @GetMapping(value = "list")
    public String list(Address address,Model model) {
        List<Address> list=addressService.list(address);
        model.addAttribute("addressList",list);
        // 获取参数
        return "user/list";
    }
    //登录
    @PostMapping(value = "login",params = {"name","phone"})
    @ResponseBody
    public AjaxResult<Address> login(String name, int phone, HttpSession session)throws LoginException {
        Address user=addressService.login(name,phone);
        session.setAttribute(CommonConstants.LOGIN_USER,user);
        System.out.println("login"+name);
        System.out.println(phone);
//        Address user1=null;
////        user1.getPhone();
        return new AjaxResult<>(user);
    }

    @PostMapping("upload")
    @ResponseBody
    public AjaxResult<String> upload(MultipartFile file) {
        if (file.isEmpty()) {
            return new AjaxResult<>(400,"请选择文件");
        }
        // 文件上传的操作
        File targetFile = new File("C:\\Users\\moon\\Desktop\\upload\\"+file.getOriginalFilename());
        try {
            file.transferTo(targetFile);
            return new AjaxResult<>("上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            return new AjaxResult<>(500,"文件上传失败");
        }
    }




}
